{include file="admin@public/header" /}

<link rel="stylesheet" href="/public/static/admin/easyui/layui-v2.6.8/css/layui.css">
<link rel="stylesheet" type="text/css" href="/public/static/admin/easyui/jeasyui/themes/icon.css">


<link href="/public/static/admin/blue/bills.css?ver=20210803202401" rel="stylesheet" type="text/css">
<style>
  /*#barCodeInsert{margin-left: 10px;font-weight: 100;font-size: 12px;color: #fff;background-color: #B1B1B1;padding: 0 5px;border-radius: 2px;line-height: 19px;height: 20px;display: inline-block;}*/
  /*#barCodeInsert.active{background-color: #23B317;}*/
  .url-box {
    padding: 5px 10px;
    line-height: 20px;
    cursor: pointer;
  }

  .url-box a {
    margin-right: 5px;
  }

  .layui-form-radio {
    margin-top: 0;
  }

  /* .gridArea{padding:7px 0;} */
  .gridArea .btns {
    padding: 0 0 7px 0;
  }

  .ui-jqgrid-bdiv tr.ui-state-highlight {
    background: #f8ff94
  }

  #filter-submit {
    float: right;
    margin-right: 80px;
  }

  .con-footer ul li label.wt55 {
    width: 55px;
  }

  #billTitle.wt190 {
    width: 320px;
  }

  .con-footer ul.maxwt-none {
    max-width: none;
  }

  .ui-jqgrid a.xhtRed {
    color: red;
  }

  .ui-jqgrid a.xhtRed:hover {
    color: red;
  }

  .con-footer .ctn-wrap {
    display: inline;
    padding: 0 6px 0 5px;
  }

  .con-footer ul li {
    min-width: 185px;
  }

  #billNo {
    width: 293px;
  }

  .layui-form-radio>i:hover,
  .layui-form-radioed>i {
    color: #3CBAFF;
  }

  #editBills {
    background: url(/css/img/edit.png);
    display: inline-block;
    width: 13px;
    height: 12px;
  }

  #check_history {
    background: green;
    border-radius: 10px 10px;
    width: 80px;
    text-align: center;
  }

  #check_history a {
    color: #fff;
  }

  .wrapper_con {
    overflow-y: auto;
    overflow-x: hidden;
  }

  .ui-jqgrid a.srcOrderNo {
    text-decoration: none;
    cursor: pointer;
  }

  .ui-jqgrid a.srcOrderNo:hover {
    text-decoration: none;
  }

  .layui-form-checkbox[lay-skin=primary]:hover i {
    border-color: #5dc5e7;
  }

  .layui-form-checked[lay-skin=primary] i {
    background-color: #5dc5e7;
  }

  .layui-form-radio {
    line-height: 30px;
  }

  .layui-form-radio *,
  .layui-form-checkbox span {
    font-size: 12px;
  }

  .con-footer ul li label {
    width: 66px;
  }

  .ui-jqgrid-bdiv .jqgrow[aria-selected='false']{
    background:none;
  }
  .ui-jqgrid-bdiv .jqgrow.ui-priority-secondary[aria-selected='false']{
    background: #f8f8f8;
  }
  .ui-jqgrid-bdiv .jqgrow[aria-selected='true']{
    background: #f8ff94;
  }
</style>
</head>


<div class="wrapper">
  <div class="mod-toolbar-top mr0 cf dn" id="toolTop"></div>
  <div class="bills cf">
    <div class="con-header layui-form">
      <dl class="l cf" style="padding-bottom: 10px;">
        <dd class="mr10">
          <label>单据日期:</label>
          <input type="date" id="startdate" class="ui-input " value="" style="width: 130px;">
          <span class="todate"> 至 </span>
          <input type="date" id="enddate" class="ui-input " value="" style="width: 130px;">
        </dd>
        <dd class="mr20">
          <label>单据编号：</label>
          <span class="ui-combo-wrap" id="">
            <input type="text" name="" class="input-txt" autocomplete="off" value="" data-ref="date"
              placeholder="多个单号用,隔开" id="sns" style="font-size: 12px;">
        </dd>
        <dd class="mr20">
          <label><span class="red"></span>供应商:</label>
          <span class="ui-combo-wrap" id="customer" style="width: 198px;">
            <i class="ui-icon-ellipsis" onclick="chooseSupplier(0,0)"></i>
            <input type="text" name="" class="input-txt" autocomplete="off" value="" data-ref="date"
              style="width: 188px;">
          </span>
          <input type="hidden" id="customerid" value="" autocomplete="off" readonly="">
        </dd>
        
        <dd id="classes" class="mr20">
          <input type="radio" name="type" value="1" title="已全部开票">
          <input type="radio" name="type" value="0" title="未全部开票" checked="">
        </dd>
        <dd id="classes" class="mr20">
          <input type="checkbox" name="showSubtotal" id="showSubtotalId" lay-skin="primary" title="税额为0不显示" value="1">
        </dd>
      </dl>
      <a class="ui-btn mrb ui-btn-search" id="search">查询</a>
      <hr class="hrcls" />
    </div>

    <!-- 功能区 -->
    <div class="gridArea" >
      <!-- 数据列表 -->
      <div class="cf btns">
        <div class="fr">
          <a id="save" onclick="savedata();" class="ui-btn-bill ui-btn-add btn-sm fl mr10">确定</a>
          <a href="#" class="ui-btn-bill ui-btn-hl btn-sm fl mr10" id="billRecord" onclick="addPage('/scm/purchasebilling/index.html','purchase','采购开票记录')">开票记录</a>
          <a href="#" class="ui-btn-bill ui-btn-hl btn-sm fl" id="export">导出</a>
        </div>
      </div>
      <div class="grid-wrap" style="margin-top: 15px;">
        <table id="grid">
        </table>
        <div id="page"></div>
      </div>
      <!-- 底部信息栏 -->
      <div class="con-footer cf" style="font-size: 12px;">
        <ul id="amountArea" class="cf maxwt-none">
          <li>
            <label class="wt55">开票日期</label>
            <input type="date" id="billDate" class="ui-input " value="" style="width: 130px;">
          </li>
          <li>
            <label class="wt55"><span class="red">*</span>发票号</label>
            <input type="text" id="billNo" class="ui-input" style="width: 293px;">
          </li>
          <li>
            <label class="wt55">发票金额</label>
            <input type="text" id="billAmount" class="ui-input ui-input-dis" disabled>
          </li>
          <li>
            <label class="wt55"><span class="red">*</span>发票抬头</label>
            <!--<input type="text" id="billTitle" class="ui-input wt190">-->
            <div class="ctn-wrap"><span id=""><span class="ui-combo-wrap ui-combo-active" style="width: 318px;"><input
                    type="text" id="billTitle" class="input-txt" autocomplete="off" style="width: 308px;"><span
                    class="aa"></span></span></span></div>
          </li>

        </ul>
      </div>
    </div>

    <!--  以隐藏的方式获取供应商类别 -->
    <div style="display:none;">
      <input type="text" id="supplierid" value="" autocomplete="off" readonly="">
    </div>

  </div>
</div>
<script type="text/javascript">
  //鼠标移开时隐藏展开的列表
  $('#toolBottom').on('mouseleave.menuEvent', '.ui-btn-menu', function (e) {
    $(this).removeClass('ui-btn-menu-cur');
  });
  $('#toolBottom').on('mouseover', '.ui-btn-menu', function (e) {
    $(this).addClass('ui-btn-menu-cur');
  });
</script>
<script type="text/javascript">
  //$action_type 0 查询 1 导出
  function grid_search_list($action_type){

      // 设置表格高度
      $(".ui-jqgrid .ui-jqgrid-bdiv").css({"max-height":$(window).height() - 330 - $("#filter-menu").height() + "px"});
       
      $("div.grid-subtitle").text("日期: " + startdate + " 至 " + enddate);
      var startdate = $('#startdate').val();
      var enddate = $('#enddate').val();
      var user_id = $("#customerid").val();//客户ID
      var sn = $("#sns").val();//单据编号
      var is_kp_all = $('input:radio[name="type"]:checked').val();//是否全部开票
      // 判断（税额为0不显示）
      var is_tax_e_zero = 0;  //默认不为0
      if ($("#showSubtotalId").get(0).checked) {
        is_tax_e_zero = 1;
      } else {
        is_tax_e_zero = 0;
      }


      if ($action_type==0) {
        var param= { 'ajax': '100', 'startdate': startdate, 'enddate': enddate, 'user_id': user_id,'is_kp_all':is_kp_all,'is_tax_e_zero':is_tax_e_zero,'sn':sn}; //发送数据 
      }else if($action_type==1){
        var param={ 'is_export':1,'ajax': '100', 'startdate': startdate, 'enddate': enddate, 'user_id': user_id,'is_kp_all':is_kp_all,'is_tax_e_zero':is_tax_e_zero,'sn':sn};
        var export_param='';
        for(let key  in param){
          export_param+=key+'='+ param[key]+'&';
        }
        export_param = export_param.substr(0, export_param.length - 1);  
        //console.log(export_param);
        window.location.href="add.html?"+export_param;
        return false;
      }
      //此处可以添加对查询数据的合法验证 
      $("#grid").jqGrid('setGridParam', {
        datatype: 'json',
        postData: param, //发送数据 
        page: 1
      }).trigger("reloadGrid"); //重新载入 
  }
</script>

<script type="text/javascript">
  var Pdata;
  var edit_row = 0;
  var edit_col = 0;
  var row_id = 0;
  var col_name = 0;

  // function cbox(cellvalue, options, rowObject) {
  //   return '<input role="checkbox" type="checkbox" id="jqg_grid_1291309293118595_0" class="cbox" name="jqg_grid_2">'
  // }

  $(document).ready(function () {
      // 获取当前日期
      var myDate = new Date;
      var year = myDate.getFullYear(); //获取当前年
      var mon = myDate.getMonth() + 1; //获取当前月
      var date = myDate.getDate(); //获取当前日
      console.log(year + '-' + mon + '-' + date)
      if (mon < 10) {
        mon = "0" + mon;
      }
      if (date < 10) {
        date = "0" + date;
      }
      $("#startdate").val(year + '-' + mon + '-01');
      $("#enddate,#billDate").val(year + '-' + mon + '-' + date);

    // 跳转打开新标签页
    $(".ta").click(function () {
      var tabid = $(this).attr('tabid');
      var tabTxt = $(this).attr('tabTxt');
      var _href = $(this).attr('_href');
      parent.tab.addTabItem({
        tabid: tabid,
        text: tabTxt,
        url: _href
      })
    });
    // 导出按钮
    $("#export").click(function () {
      grid_search_list(1);//0 查询 1 导出
    });

    // 点击查询按钮
    $("#search").click(function () {
      grid_search_list(0);//0 查询 1 导出
    });

    var idlist=[];
    $("#grid").jqGrid({
      url: '/scm/purchasebilling/add.html?ajax=100',
      datatype: "json",//数据来源，本地数据（local，json,jsonp,xml等）
      height: "300px",//高度，表格高度。可为数值、百分比或'auto'
      colNames: ["id", "单据日期", "单据编号", "供应商", "金额", "税额", "付款状态", "价税合计", "已开票金额", "未开票金额", "<span class='red'>*</span>本次开票金额",'o_type'],
      colModel: [
        { name: 'id', index: 'id', width: 40, hidden: true },
        { name: 'dj_time', width: 100, label: "单据日期" },
        { name: 'sn', index: '', width: 120, label: "单据编号" },
        { name: 'c_name', index: '', width: 200, label: "供应商", },
        { name: 'jine_sum', width: 100, label: "金额", editable: false , align:"right" },
        { name: 'tax_e_sum', index: '', width: 100, label: "税额", editable: false, align:"right" },
        { name: 'pay_status_name', index: '', width: 80, label: "付款状态", editable: false },
        { name: 'total_price_sum', index: '', width: 100, label: "价税合计", editable: false , align:"right"},
        { name: 'y_invoice_price', index: '', width: 100, label: "已开票金额", editable: false , align:"right"},
        { name: 'w_invoice_price', index: '', width: 100, label: "未开票金额", editable: false, align:"right" },
        { name: 'invoice_price', index: '', width: 100, label: "本次开票金额", editable: true , align:"right"},
        { name: 'o_type', hidden: true },
      ],
      cellEdit: true,
      cellurl: '/',
      rowNum: 100,
      rowList: [100, 200, 500],
      sortname: 'id',
      sortorder: "desc",
      pagerpos: "left",//分页位置
      multiselect: true,

      pgbuttons: true,//翻页按钮
      pagination: true,
      altRows: !0,
      gridview: !0,
      shrinkToFit: !1,
      cellLayout: 8,
      autowidth: !0,
      pager: "#page",
      viewrecords: !0,
      cmTemplate: {
        sortable: !1,
        title: !1
      },
      // 合计
      footerrow: true,
      gridComplete: function () {
        var grid = $("#grid");
       
        var ids = grid.getDataIDs();
        var rowDatas = grid.jqGrid("getRowData");//获取所有行的数据
        //alert(col_hs);
        for (var i = 0; i < ids.length; i++) {
          var rowData = rowDatas[i];
          if (rowData.o_type == "5") {
            $("#" + ids[i] + " td").css("color", "#ff0000");
          }
        }
        // 设置表格高度
        $(".ui-jqgrid .ui-jqgrid-bdiv").css({"max-height":$(window).height() - 330 - $("#filter-menu").height() + "px"});

        var after_discounts = parseFloat($("#grid").getCol('after_discount', false, 'sum')).toFixed(2);
        var discount_rates = parseFloat($("#grid").getCol('discount_rate', false, 'sum')).toFixed(2);
        var total_arrears_moneys = parseFloat($("#grid").getCol('total_arrears_money', false, 'sum')).toFixed(2);
        var y_invoice_prices = parseFloat($("#grid").getCol('y_invoice_price', false, 'sum')).toFixed(2);
        var w_invoice_prices = parseFloat($("#grid").getCol('w_invoice_price', false, 'sum')).toFixed(2);
        var invoice_prices = parseFloat($("#grid").getCol('invoice_price', false, 'sum')).toFixed(2);
        $("#grid").footerData('set', { "addtime": '合计：', after_discount: after_discounts, discount_rate:discount_rates, total_arrears_money:total_arrears_moneys, y_invoice_price:y_invoice_prices, w_invoice_price:w_invoice_prices, invoice_price:invoice_prices });
      
        // 合并合计单元格
				var $footRow = $("#grid").closest(".ui-jqgrid-bdiv").next(".ui-jqgrid-sdiv").find(".footrow");
				$footRow.find('>td[aria-describedby="grid_cb"], >td[aria-describedby="grid_addtime"], >td[aria-describedby="grid_sn"]').css("border-right-color", "transparent");
      },
      loadError: function (t, e, i) {
        parent.Public.tips({
          type: 1,
          content: "操作失败了哦，请检查您的网络链接！"
        })
      },
      beforeEditCell: function (rowid, cellname, value, iRow, iCol) {
        col_name = cellname;
        edit_row = iRow;
        edit_col = iCol;
        row_id = rowid;
        var gname = $("#grid").jqGrid("getCell", row_id, 'goodsname');
        $("#goodsname").val(gname);

      },

      onCellSelect: function (rowid, iCol, cellcontent, e) {
          var checkedState = $("#grid #jqg_grid_" + rowid).prop("checked");  //获取当前点击行是否选中
          // console.log(iCol);
          var rowData = $("#grid").jqGrid('getRowData',rowid).w_invoice_price;

          // console.log(rowData);
          if(iCol==11){
            
          }else if(iCol==0){
            checkedState=!checkedState;
            if (checkedState) {
              //idlist.splice($.inArray(rowid,idlist),1);
              $("#grid #jqg_grid_" + rowid).prop("checked", true);//打钩，
              $("#grid").jqGrid("setCell", rowid, 'invoice_price', rowData);
              // $("#grid #" + rowid).css({ "background": "#fff" });//样式
            } else {
              
              //idlist.push(rowid);
              $("#grid #jqg_grid_" + rowid).prop("checked", false);
              // $("#grid #" + rowid).css({ "background": "#f8ff94" });
            }
          }else{
            if (checkedState) {
             
              //idlist.splice($.inArray(rowid,idlist),1);
              $("#grid #jqg_grid_" + rowid).prop("checked", false);
              $("#grid").jqGrid("setSelection", rowid, false);
               // $("#grid #" + rowid).css({ "background": "#fff" });
            } else {
             
               //idlist.push(rowid);
              $("#grid #jqg_grid_" + rowid).prop("checked", true);
              $("#grid").jqGrid("setSelection", rowid, true);
              $("#grid").jqGrid("setCell", rowid, 'invoice_price', rowData);
              // $("#grid #" + rowid).css({ "background": "#f8ff94" });
            }
           
          }
          if(iCol!=11){
            if($.inArray(rowid,idlist)==-1){
              idlist.push(rowid);
            }else{
              idlist.splice($.inArray(rowid,idlist),1);
            }
          }
         // var select_rowid = $("#grid").jqGrid("getGridParam", "selarrrow");
          select_rowid(idlist);
        
      },
      onSelectAll : function(rowids,status){
        if (status) {
          select_rowid(rowids);
        }else{
          select_rowid([]);
        } 
      },
      

      beforeSaveCell: function (rowid, cellname, value, iRow, iCol) {
        edit_row = iRow;
        edit_col = iCol;
        row_id = rowid;

        // 编辑本次开票金额
        var select_rowids = $("#grid").jqGrid("getGridParam", "selarrrow");
        select_rowid(select_rowids);

        var after_discounts = parseFloat($("#grid").getCol('after_discount', false, 'sum')).toFixed(2);
        var discount_rates = parseFloat($("#grid").getCol('discount_rate', false, 'sum')).toFixed(2);
        var total_arrears_moneys = parseFloat($("#grid").getCol('total_arrears_money', false, 'sum')).toFixed(2);
        var y_invoice_prices = parseFloat($("#grid").getCol('y_invoice_price', false, 'sum')).toFixed(2);
        var w_invoice_prices = parseFloat($("#grid").getCol('w_invoice_price', false, 'sum')).toFixed(2);
        var invoice_prices = parseFloat($("#grid").getCol('invoice_price', false, 'sum')).toFixed(2);
        $("#grid").footerData('set', { "addtime": '合计：', after_discount: after_discounts, discount_rate:discount_rates, total_arrears_money:total_arrears_moneys, y_invoice_price:y_invoice_prices, w_invoice_price:w_invoice_prices, invoice_price:invoice_prices });
      

      },
    });    

  });



</script>

<script type="text/javascript">

  function select_rowid(idlist){
    var select_rowid =idlist;
    // console.log("A:",idlist);
    var money = 0;
    select_rowid.forEach(function (self, index) {
      //console.log(self);
      var get_data_from_id = $("#grid").jqGrid("getRowData",self).invoice_price;
      money = money / 1 + get_data_from_id / 1;
    });
    $('#billAmount').val(money);
  }
  
  

  //获取表格选中数据
  function selectdata() {
    var rowid = $("#grid").jqGrid("getGridParam", "selarrrow");
    var arr = new Array();
    for (let index = 0; index < rowid.length; index++) {
      var element = rowid[index];
      var rowData = jQuery("#grid").jqGrid("getRowData", element);
      arr[index] = rowData;
    }
    return arr;
  }

  $(".wrapper").on("click", "#savaAndAdd", function (e) {
    //先保存
    if (edit_row != 0 && edit_col != 0) {
      $("#grid").jqGrid("saveCell", edit_row, edit_col);
      edit_row = 0;
      edit_col = 0;
    }
  })


  function savedata() {
    var movedata = selectdata();
    var dj_time = $("#billDate").val();
    var invoice_price = $("#billAmount").val();
    var invoice_no = $("#billNo").val();
    var invoice_title = $('#billTitle').val();

    // 循环判断是否填写本次开票金额
    var flag = 0;
    movedata.forEach(function (self, index) {
      if (self['invoice_price'] == null || self['invoice_price'] == "") {
        flag++;
      }
    });

    if(invoice_no=="" || invoice_no==null){
      layer.msg("请输入发票号！");
      return false;
    } else if(invoice_title=="" || invoice_title==null){
      layer.msg("请输入发票抬头！");
      return false;
    } else  if(movedata==[] || movedata=="" || movedata==null){
      layer.msg("请选择至少一条单据记录！");
      return false;
    }else if(flag != 0){
      layer.msg("请填写本次开票金额！");
      return false;
    }else{
      $.ajax({
        type: 'POST',
        url: "save.html",
        data: { dj_time: dj_time, invoice_price: invoice_price, invoice_no: invoice_no, invoice_title: invoice_title, movedata: movedata },
        dataType: "json",
        async: false,
        error: function (request) {
          layer.msg("发送请求失败！");
        },
        success: function (data) {
          if (data.status == 1) {
            layer.msg(data.msg);

            setTimeout(function () {
              location.reload();
            }, 2900);
            
          } else {
            layer.msg(data.msg);
          }

        }
      });
    }

  }

</script>

{include file="admin@public/footer" /}